import sys
import joblib
import matplotlib.pyplot as plt
import csv
import numpy as np

"""*******************"""

from scipy.interpolate import interp1d

"""
@brief: 拉伸时间序列到指定长度并做线性插值填充序列 
@param: curve_samples 二维列表[ [序列1] , [序列2] , ... , [序列n] ]
        target_length 拉伸到指定长度
@ret:   拉伸插值后的时间序列
"""
def stretch_and_interpolate(curve_samples, target_length):
    
    # 初始化一个数组来存储插值填充后的曲线
    interpolated_curves = np.zeros((len(curve_samples), target_length))
    
    # 对每个曲线进行插值填充
    for i, curve in enumerate(curve_samples):
        # 使用插值方法
        f = interp1d(np.linspace(0, 1, len(curve)), curve)
        # 计算插值填充后的曲线
        interpolated_curve = f(np.linspace(0, 1, target_length))
        interpolated_curve_rounded = np.around(interpolated_curve, decimals=1)
        # 将插值填充后的曲线存储到数组中
        interpolated_curves[i] = interpolated_curve_rounded
    
    return interpolated_curves

"""
@brief  读取指定路径文件，格式为
        [Label] [point0] [point1] [point2] ... [pointN]
        [Label] [point0] [point1] [point2] ... [pointN]
        ...
        [Label] [point0] [point1] [point2] ... [pointN]
        @Label 1为异常类 0为正常类 可以多分类 例如每种吸液量分一类
@param  file_path 指定文件路径
@ref    样本数据data_x
        标签数据data_y
"""
def read_and_convert(file_path):
    data = []
    with open(file_path, newline='') as csvfile:
        # 创建一个 CSV 读取器对象
        csv_reader = csv.reader(csvfile)
        # 逐行读取 CSV 文件内容并打印出来
        for row in csv_reader:
            result = ",".join(row)
            data.append(result)

    string_list = []
    for item in data:
        string_list.append(item)
        
    data_X = []
    data_y = []    
    for string in string_list:
        # 分割字符串并将每个数字字符串转换为整数
        number_list_X = [int(num) for num in string[2:].split(',')]
        number_list_Y = [int(num) for num in string[0]]
        data_X.append(number_list_X)
        data_y.append(number_list_Y)
    return data_X, data_y

"""
@brief  z-score标准化数据预处理 
@param  data np.array二维数组
@ret    归一化后数据
"""
def z_score_standardization(data):
    # 计算均值和标准差
    mean = np.mean(data)
    std = np.std(data)
    
    # 对数据进行Z-score标准化
    z_score_data = (data - mean) / std
    
    return z_score_data

def model_predict(model_path, test_data, test_y):
    try:
        print("Loaded model from disk")
        model = joblib.load(model_path)
    except:
        print("No existing model found...")
    
    scores = model.decision_function(test_data)
    threshold = -0.001  # 可以根据需要调整异常得分的阈值
    is_outlier = scores < threshold  
    print("判断结果：", is_outlier)
    from sklearn.metrics import accuracy_score
    accuracy = accuracy_score(test_y, is_outlier)
    print("accuracy:", accuracy)
    # 可视化异常得分
    plt.figure(figsize=(10, 5))
    plt.plot(scores, marker='.', linestyle='-')
    plt.axhline(y=threshold, color='r', linestyle='--', label='Threshold')
    plt.xlabel("Time Series Index")
    plt.ylabel("Anomaly Score")
    plt.title("Anomaly Scores of Time Series")
    plt.legend()
    plt.show()
    plt.close()
    
def read_data(filename):
    try:
        test_data_x, test_data_y = read_and_convert(filename)
    except:
        print("Cannot read data file...")
    interpolated_test_x = stretch_and_interpolate(test_data_x, 300)
    x_test = np.array(interpolated_test_x)
    x_test = z_score_standardization(x_test)
    y_test = np.array(test_data_y)
    return x_test, y_test

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: demo.py <model_path> <Tdata_path>")
        sys.exit(1)
        
    np.set_printoptions(threshold=np.inf)
    model_path = sys.argv[1]
    test_path = sys.argv[2]
    x,y = read_data(test_path)
    model_predict(model_path,x,y)